package server;

import helpers.GamerThread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector; 

import objects.DominoGame;
import objects.Player;


public class DominoServer {
	
	int serverPort;
	int clientCounter=0;
	int clientLimit = 2;//8;
	
	ServerSocket listenSocket;
	
	public Vector<Player> players;
	
	public DominoGame dominoGame;
	
	public DominoServer(){
		 serverPort = 7896; // the server port
		 dominoGame = new DominoGame();
		 try {
			listenSocket = new ServerSocket(serverPort);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void listenConnections(){
		try{
			
			while(true) {
				if(clientCounter < clientLimit){
					
					Socket clientSocket = listenSocket.accept();
					System.out.println("Incoming connection!");
					//each connection gets a worker thread that will attend each of the petitions of the client
					GamerThread c = new GamerThread(clientSocket, dominoGame);
					c.setActive(true);
					c.start();					
					clientCounter++;
					if(clientCounter==clientLimit){
						dominoGame.broadcastStartGame();
					}
				}
				
			}
		} catch(IOException e) {System.out.println("Listen socket:"+e.getMessage());}
		
	}
	
	public static void main (String args[]) {
		DominoServer dominoServer = new DominoServer();
		dominoServer.listenConnections();
	}
}
